<?php
namespace app\index\controller;
use think\Controller;
use think\facade\Request;
use think\Validate;
use think\facade\Log;

class Index extends Controller
{


    function http_curl($url)
    {
        // 1.初始化curl
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//禁止调用时就输出获取到的数据
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }



    public function getRealyAddress($lat,$lng)
    {
        $address = '';
        if($lat && $lng){
            $arr = $this->changeToBaidu($lat,$lng);
            $url = 'http://api.map.baidu.com/geocoder/v2/?callback=&location='.$arr['y'].','.$arr['x'].'.&output=json&pois=1&ak=VFBXcU0sz3jUN3GQrTe6eDqm';
            $content = file_get_contents($url);
            $place = json_decode($content,true);
            //$address = $place['result']['formatted_address'];
            $address = $place['result']['addressComponent']['city'];
        }
        return $address;
    }


    /**
     * [changeToBaidu 转换为百度经纬度]
     * @author sunlq 2018-05-28
     * @param  [type] $lat [description]
     * @param  [type] $lng [description]
     * @return [type]  [description]
     */
    public function changeToBaidu($lat,$lng)
    {
        $apiurl = 'http://api.map.baidu.com/geoconv/v1/?coords='.$lng.','.$lat.'&from=1&to=5&ak=VFBXcU0sz3jUN3GQrTe6eDqm';
        $file = file_get_contents($apiurl);
        $arrpoint = json_decode($file, true);
        return $arrpoint['result'][0];
    }


    /**
     * 用户登陆
     * @return [type] [description]
     */
    public function  userlogin()
    {
        $param = input('param.');
        $code = $param['code'];
        $lat  = !empty($param['latitude'])?$param['latitude']:'';
        $lng  = !empty($param['longitude'])?$param['longitude']:'';
        if(isset($param['user_id'])&&isset($param['pass'])&&$param['pass']=='dongdongidea') {

        }

	//$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxc0335e3b3704e50f&secret=1da04d1fa8f647d595967ec31ccb3454&js_code='.$code.'&grant_type=authorization_code';
	$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxdbd8dd51f9eda999&secret=635fb119e6a065c99c602faeb1f80157&js_code='.$code.'&grant_type=authorization_code';
	$result = $this->http_curl($url);
        $json = json_decode($result, true);
        if(!empty($json['errcode'])){
            $this->ajaxReturn($json, '登陆错误', 201);
        }
        unset($json['session_key']);
        $user = db('user')->where('openid', $json['openid'])->field('id,nickName,avatarUrl,status')->find();

        if(empty($user)){
            $json['status'] = 1;

            $userId = db('user')->insertGetId($json);
            $user = db('user')->where('openid', $json['openid'])->field('id,nickName,avatarUrl,status')->find();
        }

        $user['city'] = $this->getRealyAddress($lat, $lng);
        $c = db('company')->where('user_id', $user['id'])->field('id,status,company_name,logo')->find();
        $h = db('bounty_hunter')->where('user_id', $user['id'])->field('id,status')->find();

        if ($user['status'] ==  3)// 公司
        {
            if (empty($c)) {
                $this->ajaxReturn($c, '公司信息不存在', 200);
            }
            $user['nickName'] = $c['company_name'];
            $user['avatarUrl'] = Request::domain().$c['logo'];
        }

        $user['status']  = $c?$c['status']:($h?$h['status']:0);
        $user['is_role'] = $c?3:($h?2:1);

        # 更新token
        $token = base64_encode(time().rand(1,999));
        db('user')->where('id', $user['id'])->update(['token'=>$token]) ;
        $user['chatkey']  = $token;

        $this->ajaxReturn($user, 'ok', 200);
    }





    /**
     * 修改用户信息
     * @return [type] [description]
     */
    public function userset()
    {
        $post = input('post.');
        $userId = $post['user_id'];
        unset($post['user_id']);
        // 转码；
        if (isset($post['nickName'])) {
            $post['nickName'] =  $this->filter($post['nickName']);
        }

        $res = db('user')->where('id', $userId)->update($post);
        if($res!==false){
            $this->ajaxReturn($res, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '失败', 204);
        }
    }

    public function filter($str) {
        if($str){
            $name = $str;
            $name = preg_replace_callback('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', function(){return ''; }, $name);
            $name = preg_replace_callback('/xE0[x80-x9F][x80-xBF]‘.‘|xED[xA0-xBF][x80-xBF]/S',function(){return '?'; }, $name);
            $return = json_decode(preg_replace_callback("#(\\\ud[0-9a-f]{3})#i",function(){return ''; }, json_encode($name)));
//                if(!$return){ return $this->jsonName($return); }
        }else{
            $return = '';
        }
        return $return;
    }



    /**
    **首页
    **/
    public function home()
    {
        $config = db('config')->field('id,ad,latitude,longitude')->find();
		if ($config) {
            $config['ad'] && $config['ad'] = explode(',', $config['ad']);
            $position = db('position')->where(['is_rec'=>1])->field('id,title,salary,region_name,sex,agemin,agemax,welfare,ctime,rebate')->select();
            $config['position'] = $position;
            $this->ajaxReturn($config, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 200);
        }
    }



    public function hometest()
    {
        $info = db('info')->select();
		if ($info) {
            $this->ajaxReturn($info, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 200);
        }
    }


    /**
     * 首页红包
     *
     * @return void
     */
    public function homeRed()
    {
        $userId = input('get.user_id');
        $share = db('share')->where(['status'=>1, 'share_id'=>$userId])->column('id');
		if ($share) {
            $this->ajaxReturn($share, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 200);
        }
    }



    public function uploads(){
        $file = request()->file('file');
        $filePath = request()->post('file_path');
        $type = request()->post('is_thumb');
        $path = 'uploads'. DS . $filePath;

        if(isset($file)){
            // 获取表单上传文件 例如上传了001.jpg
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(PATH . DS . $path);
            //var_dump($info) ;die;

            if($info){
                // 成功上传后 获取上传信息
                $a = $info->getSaveName();
                $imgp = str_replace("\\","/",$a);
                $imgpath = $path . DS . $imgp;

                $filename =  basename($info->getFilename(),'.'.$info->getExtension());
                $return =  DS . $imgpath;
                if($type){
                    //缩略图
                    $thumb = $path . DS . pathinfo($a, PATHINFO_DIRNAME) . DS . $filename . '_thumb_200.' . $info->getExtension();
                    $image = \think\Image::open($imgpath);
                    $image->thumb(300, 300)->save($thumb);
                    $return = DS . $thumb;
                }

                $image = \think\Image::open($imgpath);
                $image->thumb(750, 750)->save($imgpath);


                $this->ajaxReturn($return, 'ok', 200);
            }else{
                //上传失败获取错误信息
                $msg = $file->getError();
                $this->ajaxReturn(null, $msg, 201);
            }
        }

    }




    public function qrcode(){}



    /**
     * 聊天数据
     *
     * @return void
     */
    public function index()
    {
        // $invite_user_id = input('get.invite_user_id');
        // $beinvite_user_id = input('get.beinvite_user_id');
        // if(empty($invite_user_id)){
        //     $this->ajaxReturn(null, '邀请人参数错误', 201);
        // }
        // if(empty($beinvite_user_id)){
        //     $this->ajaxReturn(null, '被邀请人参数错误', 201);
        // }

        // $chat = db('chat')
        // ->where(['invite_user_id'=>$invite_user_id ,'beinvite_user_id'=>$beinvite_user_id])
        // ->whereOr(['invite_user_id'=>$beinvite_user_id, 'beinvite_user_id'=>$invite_user_id])
        // ->select();
		// if ($chat) {
        //     dump(json_encode($chat));
        // }else{
        //     dump('');
        // }

        //$data = db('chat')->select();
        //exit(json_encode($data));
        return $this->fetch();
    }




    /**
     * 消息发送
     *
     * @return void
     */
    public function message()
    {
        $invite_user_id = input('post.invite_user_id');
        $beinvite_user_id = input('post.beinvite_user_id');
        $content = input('post.content');
        if(empty($invite_user_id)){
            $this->ajaxReturn(null, '邀请人参数错误', 201);
        }
        if(empty($beinvite_user_id)){
            $this->ajaxReturn(null, '被邀请人参数错误', 201);
        }
        if(empty($content)){
            $this->ajaxReturn(null, '无聊天内容', 201);
        }
        $data['invite_user_id'] = $invite_user_id;
        $data['beinvite_user_id'] = $beinvite_user_id;
        $data['content'] = $content;
        $data['ctime'] = time();
        $res = db('chat')->insertGetId($data);
    }


    public function log(\think\Request $request){
        $start = $request->get('start',0);
        $end = $request->get('end',15);
        $data = db('log')->order('id','desc')->limit($start, $end)->select();
        dd($data);
    }


}
